package com.icinfo.cloud.provider.common.client.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.icinfo.cloud.provider.common.client.IUserCenterClient;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.AuthHeaderUtil;
import com.icinfo.cloud.provider.punish.dto.CheckObjectDeleteZlgztzs;
import com.icinfo.cloud.provider.punish.dto.CheckObjectInfoBySourceIdDto;
import com.icinfo.cloud.provider.punish.dto.CheckObjectInfoBySourceIdRequest;
import com.icinfo.cloud.provider.punish.dto.CheckObjectSaveZlgztzsDto;
import com.icinfo.cloud.provider.punish.vo.TaskClientVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 检查-usercenter client接口类
 *
 * @author Junfeng.Chen
 * @date 2024/2/6 10:11
 **/
@Slf4j
@Component
public class UserCenterClient implements IUserCenterClient {
    /**
     * userCenter项目 请求路径前缀
     */
    @Value("${member.url}")
    private String url;

    /**
     * 根据检查对象id获取检查对象相关信息
     */
    @Value("${member.api.getCheckObjectInfoBySourceId}")
    private String getCheckObjectInfoBySourceId;
    /**
     * 保存责令改正通知书调用检查接口
     */
    @Value("${member.api.saveDocumentToCheck}")
    private String saveDocumentToCheck;
    /**
     * 删除责令改正通知书调用检查接口
     */
    @Value("${member.api.deleteDocumentToCheck}")
    private String deleteDocumentToCheck;


    /**
     * get请求
     *
     * @param api    api相对路径
     * @param params 参数
     * @return 响应结果 data字段数据
     */
    private String httpGet(String api, Object params) {
        Map<String, String> headers = AuthHeaderUtil.authHeader();
        //发起get请求
        String resultBody = "";
        try (HttpResponse response = HttpUtil.createGet(assemblyApi(api))
                .addHeaders(headers).form(JSONObject.parseObject(JSON.toJSONString(params)))
                .execute()) {
            resultBody = response.body();
        }
        return getResponseData(resultBody);
    }

    private String httpPost(String api, Object params) {
        Map<String, String> headers = AuthHeaderUtil.headerInfo();
        //发起post请求
        String resultBody = "";
        try (HttpResponse response = HttpUtil.createPost(assemblyApi(api))
                .addHeaders(headers).body(JSON.toJSONString(BeanUtil.beanToMap(params)))
                .execute()) {
            resultBody = response.body();
        }
        return getResponseData(resultBody);
    }

    /**
     * 获取响应data
     *
     * @param resultBody 响应body
     * @return
     */
    private String getResponseData(String resultBody) {
        JSONObject response = JSON.parseObject(resultBody);
        if (HttpStatus.HTTP_OK != response.getInteger("code")) {
            throw new BusinessException(response.getString("message"));
        }
        return response.getString("data");
    }


    /**
     * 组装api完整路径
     *
     * @param api 接口相对路径
     * @return 完整api路径
     */
    private String assemblyApi(String api) {
        return url + api;
    }


    @Override
    public void checkObjectSaveZlgztzs(CheckObjectSaveZlgztzsDto dto) {
        httpPost(saveDocumentToCheck, dto);
    }

    @Override
    public void checkObjectDeleteZlgztzs(CheckObjectDeleteZlgztzs dto) {
        httpPost(deleteDocumentToCheck, dto);
    }

    @Override
    public TaskClientVO getCheckObjectInfoBySourceId(CheckObjectInfoBySourceIdDto dto) {
        CheckObjectInfoBySourceIdRequest request = new CheckObjectInfoBySourceIdRequest();
        request.setClientId(dto.getSourceId());
        request.setTaskOrgId(dto.getTaskOrgId());
        String data = httpGet(getCheckObjectInfoBySourceId, request);
        TaskClientVO taskClientVO = JSON.parseObject(data, new TypeReference<TaskClientVO>() {
        });
        taskClientVO.setCheckDate(formatterCheckDate(taskClientVO.getCheckDate()));
        return taskClientVO;
    }

    /**
     * 将"yyyy-MM-dd" 转为 "yyyy年M月d日"
     */
    private static String formatterCheckDate(String checkDate) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
        LocalDate date = LocalDate.parse(checkDate, inputFormatter);
        return date.format(outputFormatter);
    }
}
